import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/enum_entity.dart';
import 'package:library_base/entities/image_entity.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/log/fb_log.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/network/transform/fb_parse_transform.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/res/widget_generator.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';
import 'package:dio/dio.dart' as dio;
import 'package:library_base/utils/get_util.dart';
import 'package:path_provider/path_provider.dart';


class MultipleImageSelectionDialog extends StatefulWidget {
  const MultipleImageSelectionDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<MultipleImageSelectionDialog> createState() =>
      _MultipleImageSelectionDialogState();
}

class _MultipleImageSelectionDialogState
    extends State<MultipleImageSelectionDialog> {
  ///从相册或相机获取合计的最大照片数量
  int maxCount = 3;

  ///水平放置多少个Item
  int crossAxisCount = 3;

  ///是否支持删除图片
  bool isSupportDelete = true;

  ///控制是否可以上传图片
  bool enableConfirm = false;

  ///已获取的图片数量
  List<ImageEntity> imageEntities = [];

  ///采购id
  late String purchaseId;

  ///回调函数
  ///parameter1：主商品(边猪)重量
  void Function()? callback;


  @override
  void initState() {
    super.initState();
    var arguments = Get.arguments;
    purchaseId = arguments['Purchase_Id'];
    callback = arguments['CallBack'];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: true,
      backgroundColor: Colors.transparent,
      body: WillPopScope(
        onWillPop: () {
          GetHelper.back();
          return Future.value(false);
        },
        child: GestureDetector(
          onTap: () => Get.back(),
          child: Container(
            alignment: Alignment.center,
            color: Colors.transparent,
            child: GestureDetector(
              onTap: () {},
              child: Container(
                width: double.infinity,
                margin: edgeH48,
                decoration: BoxDecoration(
                  color: ThemeUtil.getTheme().colorScheme.secondary,
                  borderRadius: const BorderRadius.all(Radius.circular(8)),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1), // 阴影的颜色
                      offset: const Offset(0, 0), // 阴影与容器的距离
                      blurRadius: 10.0, // 高斯的标准偏差与盒子的形状卷积。
                      spreadRadius: 0.0, // 在应用模糊之前，框应该膨胀的量。
                    ),
                  ],
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Stack(
                      children: [
                        Container(
                            padding: EdgeInsets.only(top: 40.w, bottom: 24.w),
                            width: double.infinity,
                            alignment: Alignment.center,
                            child: Text(MultiLanguage.uploadPictures.tr,
                                style: normalTextColor34)),
                        Positioned(
                          right: 0,
                          child: GestureDetector(
                            onTap: () {
                              GetHelper.back();
                            },
                            child: Container(
                              color: Colors.transparent,
                              padding: EdgeInsets.only(
                                  right: 40.w,
                                  left: 40.w,
                                  bottom: 29.w,
                                  top: 40.w),
                              child: LocalImage('common_close',
                                  width: 26.r,
                                  height: 26.r,
                                  package: Constant.packLib()),
                            ),
                          ),
                        )
                      ],
                    ),
                    line1,
                    GridView(
                      shrinkWrap: true,
                      padding: EdgeInsets.all(36.w),
                      children: buildItem(),
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: crossAxisCount,
                        mainAxisSpacing: 20.w,
                        crossAxisSpacing: 20.w,
                        childAspectRatio: 1,
                      ),
                    ),
                    line1,
                    GradientButton(
                      ThemeUtil.getTheme(),
                      margin: EdgeInsets.symmetric(vertical: 36.w,horizontal: 24.w),
                      colors: ThemeUtil.getTheme().buttonRight1BgColor(),
                      width: double.infinity,
                      height: 77.w,
                      text: MultiLanguage.determine.tr,
                      onPressed: enableConfirm ? _confirm : null,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }

  List<Widget> buildItem() {
    List<Widget> widgets = [];

    for (int i = 0; i < imageEntities.length; i++) {
      ImageEntity imageEntity = imageEntities[i];
      widgets.add(buildImageItem(imageEntity));
    }
    if (imageEntities.length < maxCount) {
      widgets.add(buildAddItem());
    }
    return widgets;
  }

  Widget buildImageItem(ImageEntity imageEntity) {
    return Stack(
      children: [
        Positioned(child: buildImage(imageEntity)),
        Visibility(
          visible: imageEntity.status == ImageLoadStatus.LOADING,
          child: Container(
            color: Colors.black12,
            width: double.infinity,
            height: double.infinity,
            alignment: Alignment.center,
            padding: edgeAll30,
            child: const CircularProgressIndicator(),
          ),
        ),
        Visibility(
          visible: imageEntity.status == ImageLoadStatus.FAIL,
          child: GestureDetector(
            onTap: () async {
              var originFile = await imageEntity.assetEntity!.originFile;
              dio.FormData formData = dio.FormData.fromMap({
                "file": await dio.MultipartFile.fromFile(
                  originFile!.path, //图片路径
                  filename: imageEntity.assetEntity!.title, //图片名称
                )
              });
              FBHttpUtil.post<Map>(context, Apis.UPLOAD,
                  params: formData,
                  requestLoading:null,
                  transformer: FBParseTransform((result) => result))
                  .then((value) {
                if (value['code'] == HttpConfig.successCode) {
                  imageEntity.status = ImageLoadStatus.SUCCESS;
                  imageEntity.imageUrl = value['data'];
                  enableConfirm = checkIsCanConfirm();
                  setState(() {});
                } else {
                  imageEntity.status = ImageLoadStatus.FAIL;
                  enableConfirm = false;
                  setState(() {});
                }
              }).catchError((err) {
                imageEntity.status = ImageLoadStatus.FAIL;
                enableConfirm = false;
                setState(() {});
              });
            },
            child: Container(
              color: Colors.black12,
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              padding: edgeAll30,
              child: Text(
                MultiLanguage.uploadFail.tr,style: secondaryTextColor26,
              ),
            ),
          ),
        ),
        Positioned(
            right: 0,
            top: 0,
            child: Visibility(
              visible: isSupportDelete && imageEntity.status != ImageLoadStatus.LOADING,
              child: GestureDetector(
                onTap: (){ _deleteItem(imageEntity); },
                child: Container(
                  padding: EdgeInsets.only(bottom: 20.w, left: 20.w),
                  child: LocalImage('common_red_close', width: 35.w, height: 35.w,package: Constant.packLib()),
                ),
              ),
            )),
      ],
    );
  }

  ///删除图片
  void _deleteItem(ImageEntity imageEntity) {
     imageEntities.remove(imageEntity);
     enableConfirm = imageEntities.isNotEmpty;
     setState(() {});
  }

  ///添加图片
  Widget buildAddItem() {
    return GestureDetector(
      onTap: () async {
        //唤起相册
        final List<AssetEntity>? result = await AssetPicker.pickAssets(
          context,
          pickerConfig: AssetPickerConfig(
            maxAssets: maxCount - imageEntities.length,
            requestType: RequestType.image,
            specialItemPosition: SpecialItemPosition.prepend,
            specialItemBuilder: (
                BuildContext context,
                AssetPathEntity? path,
                int length,
                ) {
              if (path?.isAll != true) {
                return null;
              }
              return Semantics(
                label: const AssetPickerTextDelegate().sActionUseCameraHint,
                button: true,
                onTapHint: const AssetPickerTextDelegate().sActionUseCameraHint,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    Feedback.forTap(context);
                    final AssetEntity? result = await _pickFromCamera(context);
                    if (result != null) {
                      final AssetPicker<AssetEntity, AssetPathEntity> picker =
                      context.findAncestorWidgetOfExactType()!;
                      final DefaultAssetPickerBuilderDelegate builder =
                      picker.builder as DefaultAssetPickerBuilderDelegate;
                      final DefaultAssetPickerProvider p = builder.provider;
                      p.currentPath =
                      await p.currentPath!.obtainForNewProperties();
                      await p.switchPath(p.currentPath!);
                      p.selectAsset(result);
                    }
                  },
                  child: const Center(
                    child: Icon(Icons.camera_enhance, size: 42.0),
                  ),
                ),
              );
            },
          ),
        );
        if(result!=null && result.isNotEmpty){
          for(int i = 0;i<result.length;i++){
            var imageEntity = ImageEntity();
            imageEntity.assetEntity = result[i];
            imageEntity.status = ImageLoadStatus.LOADING;
            imageEntities.add(imageEntity);
          }
          setState(() {});
          uploadImage(0);
        }
      },
      child: roundLocalImage('common_add_image',
          padding: edgeAll51,
          decoration: BoxDecoration(
            color: ThemeUtil.getTheme().secondaryBgColor(),
            borderRadius: const BorderRadius.all(Radius.circular(8)),
            border: Border.all(color: ThemeUtil.getTheme().sixthTextColor())
          ),
          package: Constant.packLib(),
          radius: double.infinity),
    );
  }

  Future<AssetEntity?> _pickFromCamera(BuildContext c) {
    return CameraPicker.pickFromCamera(
      c,
      pickerConfig: const CameraPickerConfig(enableRecording: true),
    );
  }


  Widget buildImage(ImageEntity imageEntity) {
    if (imageEntity.assetEntity != null) {
      return Container(
          child: createFutureBuilder(imageEntity),
          width: double.infinity,
          height: double.infinity,
          decoration: rs8,
          clipBehavior: Clip.hardEdge);
    } else {
      return Container();
    }
  }

  ///异步创建图片组件
  Widget createFutureBuilder(ImageEntity imageEntity) {
    return FutureBuilder<File>(
        future: localImageFile(imageEntity),
        builder: (BuildContext context, AsyncSnapshot<File> snapshot) {
          Widget widget;
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              widget = const Icon(
                Icons.error,
                color: Colors.red,
                size: 48,
              );
            } else {
              File assetFile = snapshot.data!;
              widget = Image.file(assetFile, fit: BoxFit.cover);
            }
          } else {
            widget = const Padding(
              padding: EdgeInsets.all(20),
              child: CircularProgressIndicator(),
            );
          }
          return SizedBox(
            height: double.infinity,
            width: double.infinity,
            child: widget,
          );
        });
  }

  ///返回文件路径信息
  Future<File> localImageFile(ImageEntity imageEntity) async {
    var originFile = await imageEntity.assetEntity!.originFile;
    return Future.value(originFile);
  }

  ///循环上传
  Future<void> uploadImage(int loadingIndex) async {
    ImageEntity imageEntity = imageEntities[loadingIndex];
    var originFile = await imageEntity.assetEntity!.originFile;

    // var dir = await getTemporaryDirectory();

    Directory? documentsDirectory = await getExternalStorageDirectory();
    DateTime dateTime= DateTime.now();

    // var uploadPath = '${documentsDirectory!.path}${Platform.pathSeparator}upload/';
    // await File(uploadPath).create(recursive: true);

    var targetPath = '${documentsDirectory!.path}${Platform.pathSeparator}upload${Platform.pathSeparator}${dateTime.toString().substring(0,19)}$loadingIndex.jpg';
    // var targetPath = dir.absolute.path +"/"+DateTime.now().millisecondsSinceEpoch.toString()+ ".jpg";

    var file = await File(targetPath).create(recursive: true);
    var result = await compressImage(originFile!);
    file.writeAsBytesSync(result);

    dio.FormData formData = dio.FormData.fromMap({
      "file": await dio.MultipartFile.fromFile(
        file.path, //图片路径
        filename: imageEntity.assetEntity!.title, //图片名称
      )
    });
    FBHttpUtil.post<Map>(context, Apis.UPLOAD,
        params: formData,
        requestLoading:null,
        transformer: FBParseTransform((result) => result))
        .then((value) {
      if (value['code'] == HttpConfig.successCode) {
        imageEntity.status = ImageLoadStatus.SUCCESS;
        imageEntity.imageUrl = value['data'];
        if((loadingIndex+1) <= (imageEntities.length-1)){
          uploadImage(loadingIndex+1);
        }else{
          enableConfirm = checkIsCanConfirm();
        }
        setState(() {});
      } else {
        imageEntity.status = ImageLoadStatus.FAIL;
        enableConfirm = false;
        setState(() {});
        if((loadingIndex+1) != (imageEntities.length-1)){
          uploadImage(loadingIndex+1);
        }
      }
    }).catchError((err) {
      imageEntity.status = ImageLoadStatus.FAIL;
      enableConfirm = false;
      setState(() {});
      if((loadingIndex+1) != (imageEntities.length-1)){
        uploadImage(loadingIndex+1);
      }
    });
  }

  Future<Uint8List> compressImage(File originFile) async{
    Uint8List result = originFile.readAsBytesSync();
    int i = 1;
    logger.i("第$i次压缩 ${originFile.readAsBytesSync().length}byte");

    for(int quality = 100;result.lengthInBytes>824 && quality>20;quality = quality-20){
      result = (await FlutterImageCompress.compressWithFile(
        originFile.path,
        quality: quality,
      ))!;
      logger.i("第$i次压缩 ${result.lengthInBytes/1024/1024}m");
      i++;
    }
    return Future.value(result);
  }


  bool checkIsCanConfirm(){
    for (int i = 0; i < imageEntities.length; i++) {
      ImageEntity imageEntity = imageEntities[i];
      if(imageEntity.status != ImageLoadStatus.SUCCESS){
        return false;
      }
    }
    return true;
  }

  ///确定录入信息
  _confirm(){
    var map = <String,dynamic>{};
    var imgs = [];
    map['purchaseId'] = purchaseId;
    for (int i = 0; i < imageEntities.length; i++) {
      ImageEntity imageEntity = imageEntities[i];
      imgs.add(imageEntity.imageUrl);
    }
    map['imgs'] = imgs;
    FBHttpUtil.post<Map>(context, Apis.PURCHASER_PAYMENT_ORDERS,
        params: map,
        requestLoading:GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result))
        .then((value) {
      if (value['code'] == HttpConfig.successCode) {
        ToastUtil.success(MultiLanguage.paySubmittedSuccess.tr);
        GetHelper.back();
        callback?.call();
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  @override
  void dispose() {
    super.dispose();
    deleteImage();
  }

  deleteImage() async{
    Directory? documentsDirectory = await getExternalStorageDirectory();
    var targetPath = '${documentsDirectory!.path}${Platform.pathSeparator}upload';
    var file = File(targetPath);
    if(file.existsSync()){
      file.delete();
    }
  }

}
